#include "UpdateWindow.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QPushButton>
#include <QTextStream>
#include <QFile>
#include <QFileInfo>
#include <QUrl>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QLabel>
#include <QProcess>
#include "plugins/plugin.h"
namespace bap {
	UpdateWindow::UpdateWindow(){
		this->setMinimumWidth(460);
		QVBoxLayout* mainlayout = new QVBoxLayout(this);
		QHBoxLayout* buttonlayout = new QHBoxLayout();

		m_MessageLabel = new QLabel(this);
		m_ProgressBar = new QProgressBar(this);
		m_ProgressBar->setOrientation(Qt::Horizontal);
		
		m_Update = new QPushButton(tr("Update"),this);
		m_Cancel = new QPushButton(tr("Cancel"),this);
		m_Update->setEnabled(false);

		buttonlayout->addWidget(m_Update);
		buttonlayout->addWidget(m_Cancel);
		mainlayout->addWidget(m_MessageLabel);
		mainlayout->addWidget(m_ProgressBar);
		mainlayout->addLayout(buttonlayout);

		m_AccessManager = new QNetworkAccessManager(this);
		connect(m_AccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(ReplyFinishedSlot(QNetworkReply*)));
		connect(m_Update, SIGNAL(clicked()), this, SLOT(Update()));
		connect(m_Cancel, SIGNAL(clicked()), this, SLOT(Cancel()));

		QFile sfile(":/qss/mainwindow.qss");
		sfile.open(QFile::ReadOnly);
		QString mainwindowqss = sfile.readAll();
		sfile.close();

		this->setStyleSheet(mainwindowqss);
		this->setVisible(false);

		CheckVersion();
	}
	UpdateWindow::~UpdateWindow(){
	}

	void UpdateWindow::Update()
	{
		QProcess process;
#ifdef WIN32
		process.startDetached("Update.exe", QStringList(m_NewVersion));
#else
		auto state = process.startDetached("./Update", QStringList(m_NewVersion));
#endif
		this->accept();
	}

	void UpdateWindow::Cancel()
	{
		this->reject();
	}

	void UpdateWindow::CheckVersion()
	{

		m_CurrentVersion = PACKAGE_VERSION;

		QUrl url("http://bap.cebsit.ac.cn/FNT/VERSION");
		QFileInfo fileInfo = url.path();
		m_Request.setUrl(url);
		m_Reply = m_AccessManager->get(m_Request);

	} 

	void UpdateWindow::ReplyFinishedSlot(QNetworkReply*reply) {
		QVariant status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
		QByteArray bytes = reply->readAll();  
		QString result(bytes); 
		m_NewVersion= result.simplified();
		std::cout << m_NewVersion.toStdString() << std::endl;
		if (m_NewVersion.size() > 8) {
			this->reject();
		}
		else {
			if (m_NewVersion > m_CurrentVersion) {
				m_MessageLabel->setText("Current Version: " + m_CurrentVersion.simplified() + ", Latest Version: " + m_NewVersion);
				m_Update->setEnabled(true);
				this->show();
			}
			else {
				m_MessageLabel->setText("Current Version: " + m_CurrentVersion.simplified() + " is the Latest Version!");
				this->reject();
			}
		}
	}

}